package com.itany.shop.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 石小俊
 * @date 2023年07月11日 9:20
 */
public class LogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤器的核心业务逻辑");
//        if(servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse){
//            HttpServletRequest request = (HttpServletRequest) servletRequest;
//            HttpServletResponse response = (HttpServletResponse) servletResponse;
//        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String ip = request.getRemoteAddr();
        String uri = request.getRequestURI();
        System.out.println(ip+"在"+new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date())+"访问了"+uri+"请求");

        // FilterChain用于判断当前过滤器是否对请求放行
        // 如果请求不放行,则停在当前过滤器中无法出去
        // 放行后请求进入下一个过滤器或者对应的Servlet中
        // 如果需要放行,则执行以下方法;如果不需要放行,则不执行以下方法即可
        chain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("销毁过滤器");
    }
}
